package com.pro.controller;

import com.pro.utils.FastDFSClientUtil;
import com.pro.utils.JsonData;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName: UploadController
 * @Author: 笑笑
 * @DATE: 2022/1/11
 * @TIME: 下午 04:44
 */
@Controller
@RequestMapping("/Upload")
public class UploadController {

    @Autowired
    private FastDFSClientUtil fsc;

    /**
     * @ClassName upload
     * @Author 谭金诚
     * @Date 2022/1/25
     * @Return list<String>
     * 上传图片到服务器
     */
    @PostMapping("/upload")
    @ResponseBody
    public JsonData fdfsUpload(@RequestParam("file") MultipartFile[] file, HttpServletRequest request) {
        List<String> path = new ArrayList<>();
        for (MultipartFile multipartFile : file) {
            try {
                //数据库文件路径
                String fileUrl = fsc.uploadFile(multipartFile);
                //前台传递路径
                request.setAttribute("msg", "成功上传文件，  '" + fileUrl + "'");
                path.add(fsc.getResAccessUrl(fileUrl));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return path != null ? JsonData.buildSuccess(path.get(0)):JsonData.buildError("服务器错误");
    }
}